import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { TabsPage } from "../tabs-page/tabs-page";
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { environment } from "../../services/environment";

@Component({
  selector: 'page-user',
  templateUrl: 'login.html'
})
export class LoginPage {
  // 角色
  public select: any = true;
  // 登录请求体
  public postBody: any = {
    UserId: "",
    PassWord: "",
    Role: "user"
  };
  constructor(
    public http: Http,
    public storage: Storage,
    public navCtrl: NavController,
    public alert: AlertController
  ) {

  }
  // 角色
  setRole(role: any) {
    if (role == 'student') {
      this.select = true;
      this.postBody.Role = "user";
    }
    if (role == 'teacher') {
      this.select = false;
      this.postBody.Role = "teach";
    }
  }
  // 登录
  login() {
    let that = this;
    this.http.post(environment.server + 'api/v1/users/login', this.postBody).map(res => res.json()).subscribe(body => {
      if (body.isSuccess == true) {
        console.log("------登录信息-----")
        console.log(body);
        that.storage.set('token', body.data.token);
        that.storage.set('Role', body.data.user.Role);
        that.storage.set('UserId', body.data.user.UserId);
        that.storage.set('PassWord', body.data.user.PassWord);
        that.storage.set('UserName', body.data.user.UserName);
        that.storage.set('updatedAt', body.data.user.updatedAt);
        if (body.data.user.Role == 'user') {
          let post: any = {
            where: {
              StudentId: body.data.user.UserId
            }
          }
          that.http.post(environment.server + 'api/v1/studentlists/view', post).map(res => res.json()).subscribe(body => {
            if (body.data) {
              that.storage.set('TeacherId', body.data.TeacherId);
              that.navCtrl.push(TabsPage);
            }
          })
        }
        setTimeout(function () {
          that.navCtrl.push(TabsPage);
        }, 200);
      }
    }, err => {
      console.log(err.json());
      that.errorAlert('帐号或密码不正确');
    })
  }
  // 弹窗
  errorAlert(tips: any) {
    let alert = this.alert.create({
      title: '提示',
      subTitle: tips,
      buttons: ['ok']
    });
    alert.present();
  }
}
